let text = require('../../../../common/util/text.js')
// /* 背景音乐 */
const xBackMusic = wx.getBackgroundAudioManager();
Page({
  data: {
    topic_id:'',
    info:{},
    play:false,
    timer:'00:00',
    navList:['学习','练习'],
    navcurrent:0,
    xPageReady:true,
    videoPlay:false,
    show:false
  },
  xChildReload: function () {
    var pages = getCurrentPages();//当前页面栈
    if (pages.length > 1) {
      var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
      beforePage.xInit();//触发父页面中的方法
      var beforePage = pages[pages.length - 3];//获取上上一个页面实例对象
      beforePage.xInfo();//触发父页面中的方法
    }
  },
  onLoad(options) {
    let that =this;
    // 主题id
    that.setData({
      topic_id:options.id,
      params:options
    })
    // 获取主题详情
    that.xInit(options.id)
    
  },
  xToSet:function(){
    this.setData({
      show:!this.data.show
    })
  },
  // 获取主题详情
  xInit:function(id){
    let that =this;
    wx.cloud.callFunction({
      name: 'soothing_exercise',
      data: {
        action: "get_topic",
        topic_id:id
      }
    }).then(res => {
      res.result.announcements= text.text(res.result.announcements)
      if(res.result.is_course_exercise_read){
        that.setData({
          navcurrent:1
        })
      }
      that.setData({
        info:res.result,
        xPageReady:false
      })
      // 动态设置BarTitle
      wx.setNavigationBarTitle({
        title: that.data.info.topic_name,
      })
    })
  },
  // 手动音频播放
  xToPlay:function(e){
      let that = this
      let params = e.currentTarget.dataset
      let index = params.index
      if(!xBackMusic.src){
        xBackMusic.src= that.data.info.practice_audio //设置播放地址
        xBackMusic.title= that.data.info.practice_audio_name //播放标题
      }
      xBackMusic.play() //背景音频播放
      that.setData({
        play:true //是否播放按钮
      })
      if(!that.data.info.is_course_exercise_read){
        that.bindendedvideo()
      }
      // 监听背景音频更新 设置播放时间
      // xBackMusic.onTimeUpdate(() => {
      //   let xNowTime = xBackMusic.currentTime
      //   let time = that.formatSeconds(xNowTime)
      //   that.setData({
      //     timer:time
      //   })
      // })
      // 监听背景音频结束
      xBackMusic.onEnded(function() { 
          that.setData({
            play:false
          })
          that.bindended()
      });
      //监听背景音频停止
      xBackMusic.onStop(function() { 
        that.setData({
          play:false,
          // timer:'00:00'
        })
      });
      //监听背景音频暂停
      xBackMusic.onPause(function() { 
        that.setData({
          play:false
        })
      });
      //监听背景音频播放
      xBackMusic.onPlay(function() { 
        that.setData({
          play:true
        })
      });
      // }else{
      //   // 课程
      //   wx.showModal({
      //     title: "提示",
      //     content: "建议了解舒缓练习",
      //     confirmText:"确定",
      //     success (res) {
      //       // 了解舒缓练习
      //       if(res.confirm){
      //         that.setData({
      //           navcurrent:0
      //         })
      //       }else{
      //         // 继续音频
      //         that.setData({
      //           [`info.is_course_exercise_read`]:true
      //         })
      //         that.bindendedvideo()
      //       }
      //     }
      //   })
      // }
  },
  // 播放时间显示
  formatSeconds(value) {
    var theTime = parseInt(value);// 秒
    var middle= 0;// 分
    var hour= 0;// 小时
    if(theTime > 60) {undefined
        middle= parseInt(theTime/60);
        theTime = parseInt(theTime%60);
        if(middle> 60) {undefined
            hour= parseInt(middle/60);
            middle= parseInt(middle%60);
        }
    }
    let h = parseInt(hour) > 0 ? parseInt(hour) + ":"  : ''
    let m = parseInt(middle) > 9 ? parseInt(middle) : '0' + parseInt(middle)
    let s = parseInt(theTime) > 9 ? parseInt(theTime) : '0' + parseInt(theTime);
    let result = h + m + ':' + s
    return result;
  },
  // 手动暂停
  xToStop:function(){
    let that =this
    that.setData({
      play:false
    })
    xBackMusic.pause()
  },
  // 音频播放结束
  bindended:function(){
    let that =this
    if(that.data.params.week){
        // if(Number(that.data.params.count)<=5){
          wx.cloud.callFunction({
            name: 'audio_video_practice',
            data: {
              action: "add_practice_punching",
              dataObj: {
                treatment_item_id: that.data.params.treatment_item_id,
                week:Number(that.data.params.week)
              }
            }
          }).then(res => {
              that.xChildReload()
              wx.navigateBack({
                delta:1
              })
          })
        // }
    }else{
      let list = ['非常有用', '有比较大的作用', '有一点点作用','完全没用']
      let exercise_help = ''
      wx.showActionSheet({
        alertText:'刚刚的练习是否对缓解疼痛有帮助?',
        itemList: list,
        success(res){
          exercise_help= list[res.tapIndex]
        },
        complete(){
            let _dataObj ={
              topic_id:that.data.info._id,
              // is_course_exercise_read:true,//阅读课程（视频）
              is_practice_audio_read:true,//音频练习结束后标记
              exercise_help:exercise_help //练习帮助
          }
          wx.cloud.callFunction({
            name: 'soothing_exercise',
            data: {
              action: "record_exercise_info",
              dataObj:_dataObj
            }
            }).then(res => {
                console.log("get_topics:", res)
            })
          }
        })
    }
  },
  // 视频开始播放
  bindplay:function(){
    this.setData({
      videoPlay:true
    })
  },
  // 视频播放结束
  bindendedvideo:function(){
    let that =this
    let _dataObj ={
      topic_id:that.data.info._id,
      is_course_exercise_read:true
    }
    wx.cloud.callFunction({
      name: 'soothing_exercise',
      data: {
        action: "record_exercise_info",
        dataObj:_dataObj
      }
    }).then(res => {
      that.setData({
        navcurrent:1
      })
    })
  },
  // 舒缓训练
  // xToVideo:function(){
  //   let that =this
  //   let params = {
  //     video:[that.data.info.course_exercise],
  //     title:''
  //   }
  //   let _dataObj ={
  //     topic_id:that.data.info._id,
  //     is_practice_audio_read:true
  //   }
  //   wx.cloud.callFunction({
  //     name: 'soothing_exercise',
  //     data: {
  //       action: "record_exercise_info",
  //       dataObj:_dataObj
  //     }
  //   }).then(res => {
  //       wx.navigateTo({
  //         url: '/subtool/pages/productother/video/index',
  //         success: function(res) {
  //           // 通过eventChannel向被打开页面传送数据
  //           res.eventChannel.emit('xToVideo', params)
  //         }
  //       })
  //   })
    
    
  // },
  xTabChange:function(e){
    this.setData({
      navcurrent:e.currentTarget.dataset.index,
      show:false
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.getBackgroundAudioManager().stop()
    // getApp().xInnerAudio()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})